#include "client.h"
#include <wtypes.h>

int         c_socket;
int         connected;

int ClientConnect( void )
{

    c_socket = SockConnect( P_DEFAULT_SERVER_HOST, P_DEFAULT_SERVER_PORT );

    if( c_socket == SOCKET_ERROR )
        return -1;

    P_SendHello( c_socket );

    ClientListenSock( c_socket );

    return 0;
}

int ClientDisconnect( void )
{
    P_SendLogout( c_socket );

    return 0;
}

int ClientIsReady( void )
{
    return connected;
}
int ClientListenSock( int socket )
{
    PACKET_HEADER_T header;
    BYTE            data[1024*16];

    while( socket != INVALID_SOCKET ) {

        if(SockWait( socket, 500 ) == 1) {

            /*if ( */SockRecvPacket( socket, &header, data )/* < 0 ) return -1*/;
            ClientProcessPacket( socket, &header, data );
            memset( data, 0, sizeof(data) );
        }
    }
    return 0;
}

int ClientProcessPacket( int socket, PACKET_HEADER_T *header, void *data )
{
	if ( !header )
		return dbgf( "ClientProcessPacket: bad header" );

    dbgf( "ClientProcessPacket: socket = %d, header.type = 0x%x", socket, header->type );

	switch( header->type ) {

        case P_ERROR:
            dbgf( "Error 0x%x", *(u_char *)data );
			ClientDisconnect();
			break;

		case P_LOGIN_HELLO_ACK:
            dbgf( "send login" );
			P_SendLogin( socket, PROTOCOL, LOGIN, PASS );
			break;

		case P_LOGIN_OK:
            dbgf( "login ok" );
			connected = 1;
			break;

		case P_MESSAGE:
			dbgf( "->>>incoming msg from %s:\n%s", header->login, (char*)data+4 );
            break;

		//case P_MSG_DELIVERY:
		//	break;

		case P_TYPING_NTF_START:
            dbgf( "->>>contact %s, start typing text", header->login );
            break;

		case P_TYPING_NTF_DONE:
            dbgf( "->>>contact %s, typing text done", header->login );
            break;

		case P_STATUS_CHANGE:
            dbgf( "->>>contact %s, change status to %d", header->login, ((PACKET_STATUS_T*)data)->id );
            break;

		case P_XSTATUS_CHANGE:
            dbgf( "->>>contact %s, change xstatus to %d", header->login, ((PACKET_STATUS_T*)data)->id );
            break;

		case P_XTEXT_REQ:
			break;
		case P_XTEXT_REQ_ANSWER:
			break;

		case P_AUTH_REQ:
			break;
		case P_AUTH_SET:
			break;

		case P_ROSTER:
			break;

		case P_USER_INFO:
			break;

		case P_VERSION:
			break;

		case P_CONTACT_REMOVED:
			 dbgf( "->>>contact %s, removed from you roster", header->login );
            break;
	}

	return 0;
}


